package com.vates.vsp.dao.implementacion;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.vates.vsp.dao.DaoBaseCliente;
import com.vates.vsp.entidades.Cliente;

@Repository(value = "clienteDao")
public class ClienteDao implements DaoBaseCliente {

	@PersistenceContext(unitName = UNIT_NAME)
	private EntityManager em;

	public void setEm(EntityManager em) {
		this.em = em;
	}

	@Transactional
	public void guardar(Cliente cliente) {
		if (cliente != null)
			em.merge(cliente);
	}

	@Transactional
	public void eliminar(Cliente cliente) {
		if (cliente != null) {
			em.remove(em.merge(cliente));
		}
	}

	@Transactional
	public Cliente buscarPorId(Long id) {
		try {
			TypedQuery<Cliente> q = em.createQuery(
					"SELECT c FROM Cliente c WHERE c.idCliente= :id",
					Cliente.class);
			return q.setParameter("id", id).getSingleResult();
		} catch (NoResultException e) {
			return null;
		}
	}

	@Transactional
	public Cliente buscarPorNombre(String nombre) {
		try {
			TypedQuery<Cliente> q = em.createQuery(
					"SELECT c FROM Cliente c WHERE c.nombre= :nombre",
					Cliente.class);
			return q.setParameter("nombre", nombre).getSingleResult();
		} catch (NoResultException e) {
			return null;
		}
	}

	@Transactional
	public List<Cliente> buscarTodos() {
		try {
			return em.createQuery("SELECT c FROM Cliente c ORDER BY c.nombre", Cliente.class).getResultList();
		} catch (NoResultException e) {
			return null;
		}
	}

	@Transactional
	public Cliente buscarPorNif(String nif) {
		try {
			TypedQuery<Cliente> q = em.createQuery("SELECT c FROM Cliente c WHERE c.nif= :nif", Cliente.class);
			return q.setParameter("nif", nif).getSingleResult();
		}catch(NoResultException e) {
			return null;
		}
	}
}
